package com.moo2u2.android.oaktononthego.locate.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ColleagueDbAdapter {

	// Database fields
	public static final String KEY_ROWID = "_id";
	public static final String KEY_NAME = "name";
	public static final String KEY_IMG = "img";
	public static final String KEY_LATITUDE = "latitude";
	public static final String KEY_LONGITUDE = "longitude";
	public static final String DB_TABLE = "customers";

	private Context context;
	private SQLiteDatabase db;
	private ColleagueDatabaseHelper dbHelper;

	public ColleagueDbAdapter(Context context) {
		this.context = context;
	}

	public ColleagueDbAdapter open() throws SQLException {
		dbHelper = new ColleagueDatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	public long createCustomer(String name, String phone, String address,
			String description) {
		ContentValues values = createContentValues(name, phone, address,
				description);

		return db.insert(DB_TABLE, null, values);
	}

	public boolean updateCustomer(long rowId, String name, String phone,
			String address, String description) {
		ContentValues values = createContentValues(name, phone, address,
				description);

		return db.update(DB_TABLE, values, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public boolean deleteCustomer(long rowId) {
		return db.delete(DB_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchAllCustomers() {
		return db.query(DB_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_IMG,
				KEY_LATITUDE, KEY_LONGITUDE }, null, null, null, null, null,
				null);
	}

	public Cursor fetchCustomer(long rowId) throws SQLException {
		Cursor mCursor = db.query(true, DB_TABLE, new String[] { KEY_ROWID,
				KEY_NAME, KEY_IMG, KEY_LATITUDE, KEY_LONGITUDE }, KEY_ROWID
				+ "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	private ContentValues createContentValues(String name, String phone,
			String address, String description) {
		ContentValues values = new ContentValues();
		values.put(KEY_NAME, name);
		values.put(KEY_IMG, phone);
		values.put(KEY_LATITUDE, address);
		values.put(KEY_LONGITUDE, description);
		return values;
	}

}